import 'vux/src/styles/reset.less';
import './booklist.scss'
import {
  Badge,
  Group,
  Cell,
  Panel,
  XButton,
  Scroller,
  Spinner,
  Flexbox,
  FlexboxItem,
  Popup,
  XInput,
  XTextarea,
  TransferDom,
  debounce
} from 'vux'

import { fetch, rap } from 'js/fetch.js'
import { hostImg } from 'js/host-config'

import axios from 'axios'

import utils from 'js/utils.js'

import { cookie } from 'vux'


let url = {
  deleteUncollectBook: 'api/books',//取消收藏图书
  postComment: 'api/book',//评论
  postReturn: 'api/book/borrows',//还书
  deleteUnResevation: 'api/book/reserves',//取消预约
  deleteCancelBook: '/api/book/borrows',//取消借书
  postCollectBook: 'api/books'
}

url = rap(url)

export default {
  props: {
    sort: {
      type: String
    },
    token: {
      type: String
    },
    bookdata: {
      type: Array
    },
    stop: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      isPop: false,
      commentTitle: '',
      bookid:'',
      commentContent: '',
      //bookList:[],
      data: [],
      showList1: true,
      scrollTop: 0,
      onFetching: false,
      bottomCount: 20,
      n4: 10,
      demo4Value: {
        pullupStatus: 'default'
      },
    }
  },
  computed: {
    lists() {
      let myArray = []
      this.data.forEach((item, index) => {
        let obj = {
          cover: `${hostImg}${item.cover}`,
          author: `${item.author}`,
          borrow_count: `${item.borrow_count}`,
          detail: `${item.detail}`,
          id: `${item.id}`,
          name: `${item.name}`,
          press: `${item.press}`,
          status: `${item.status}`,
          book_id: `${item.book_id}`,
          inventory: `${item.inventory}`,
          borrowed: `${item.borrowed}`,
          collected: `${item.collected}`
        }
        myArray.push(obj)
      });
      return myArray
    }
  },
  watch: {
    bookdata(val, oldVal) {
      this.$set(this, 'data', this.bookdata);
    }
  },
  created() {
    this.siteName=window.localStorage.getItem('siteName')
    this.siteID=window.localStorage.getItem('siteID')
    console.log(this.siteName)
    console.log(this.siteID)   
    this.$set(this, 'data', this.bookdata);
  },
  methods: {

    authority(item) {
      
      //鉴定是否能够操作 false不能进行按钮才做 true可以



      //检测是否登录 有登录就趣一下token
      
      
      this.isLogin = utils.isLogin()
      //console.log(this.isLogin)
      //没有登录去登录

      if (!this.isLogin) {
        //return false
        window.location.href = './login.html'
      } else {
        //取得token
        this.token = cookie.get('token')
        //判断有没交押金或是会员有没过期
        if ((Number(window.localStorage.getItem('deposit'))) > 0 && window.localStorage.getItem('isExpired') == '0') {
          return true
        } else {
          //return false
          window.location.href = './buy_member.html'
        }
      }
    },
    reservation(id) {
      //预定按钮
      //检查是否交了押金

      if (!this.authority()) {
        return
      }

      fetch('post', `${url.getRecommendBooks}/${id}/reserve`, {}, { 'headers': this.token }).then(res => {
        if (res.status >= 200 && res.status <= 300) {
          this.$vux.toast.show({
            text: '预约成功',
            onShow() {
              //console.log('Plugin: I\'m showing')
            },
            onHide() {
              window.location.href = window.location.href
              //console.log('Plugin: I\'m hiding')
            }
          })
        } else {

          this.$vux.toast.show({
            text: res.data.message,
            type: 'warn',
            onShow() {
              //console.log('Plugin: I\'m showing')
            },
            onHide() {
              //console.log('Plugin: I\'m hiding')
            }
          })
        }
      })
    },
    borrow(id) {
      
      //借阅按钮
      //检查是否交了押金
      if (!this.authority()) {
        return
      }

      fetch('post', `${url.postCollectBook}/${id}/borrow`, {}, { 'headers': this.token }).then(res => {
        if (res.status >= 200 && res.status <= 300) {
          this.$vux.toast.show({
            text: '借阅成功,请尽快领取书籍！',
            onShow() {
              //console.log('Plugin: I\'m showing')
            },
            onHide() {
              window.location.href = window.location.href
              //console.log('Plugin: I\'m hiding')
            }
          })
        } else {
          this.$vux.toast.show({
            text: res.data.message,
            type: 'warn',
            onShow() {
              //console.log('Plugin: I\'m showing')
            },
            onHide() {
              //console.log('Plugin: I\'m hiding')
            }
          })
        }
      })
    },
    unBorrow(item) {
      //取消借书
      //api/book/borrows/{borrow}/cancel
      fetch('post', `${url.deleteCancelBook}/${item.id}/cancel`, {
      }, { 'headers': this.token }).then(res => {
        if (res.status >= 200 && res.status <= 300) {
          //console.log(res.data)
          this.$vux.toast.show({
            text: '成功取消',
            onShow() {
              //console.log('Plugin: I\'m showing')
            },
            onHide() {
              window.location.href = window.location.href
              //console.log('Plugin: I\'m hiding')
            }
          })

        } else {
          this.$vux.toast.show({
            text: res.data.message,
            type: 'warn',
            onShow() {
              //console.log('Plugin: I\'m showing')
            },
            onHide() {
              //console.log('Plugin: I\'m hiding')
            }
          })
        }
      })


    },
    unResevation(item) {



      //delete /api/v2/book/reserves/{reserve}
      //
      //
      //
      //
      //
      //


      //取消预定
      fetch('delete', `${url.deleteUnResevation}/${item.id}`, {
      }, { 'headers': this.token }).then(res => {
        if (res.status >= 200 && res.status <= 300) {
          //console.log(res.data)
          this.$vux.toast.show({
            text: '成功取消',
            onShow() {
              //console.log('Plugin: I\'m showing')
            },
            onHide() {
              window.location.href = window.location.href
              //console.log('Plugin: I\'m hiding')
            }
          })

        } else {
          this.$vux.toast.show({
            text: res.data.message,
            type: 'warn',
            onShow() {
              //console.log('Plugin: I\'m showing')
            },
            onHide() {
              //console.log('Plugin: I\'m hiding')
            }
          })
        }
      })
    },
    returnBook(item) {
      //还书
      fetch('post', `${url.postReturn}/${item.id}/return`, {
      }, { 'headers': this.token }).then(res => {
        if (res.status >= 200 && res.status <= 300) {
          //console.log(res.data)
          this.$vux.toast.show({
            text: '成功还书',
            onShow() {
              //console.log('Plugin: I\'m showing')
            },
            onHide() {
              window.location.href = window.location.href
              //console.log('Plugin: I\'m hiding')
            }
          })

        } else {
          this.$vux.toast.show({
            text: res.data.message,
            type: 'warn',
            onShow() {
              //console.log('Plugin: I\'m showing')
            },
            onHide() {
              //console.log('Plugin: I\'m hiding')
            }
          })
        }
      })
    },
    comment(item) {
      let _this = this
      //提交评论
      fetch('post', `${url.postComment}/${this.bookid}/comments`, {
        title: this.commentTitle,
        content: this.commentContent,
      }, { 'headers': this.token }).then(res => {
        if (res.status >= 200 && res.status <= 300) {
          this.$vux.toast.show({
            text: '提交评论成功',
            onShow() {
              //console.log('Plugin: I\'m showing')
            },
            onHide() {
              _this.isPop = false;
              window.location.href = window.location.href
              //console.log('Plugin: I\'m hiding')
            }
          })

        } else {
          this.$vux.toast.show({
            text: res.data.message,
            type: 'warn',
            onShow() {
              //console.log('Plugin: I\'m showing')
            },
            onHide() {
              //console.log('Plugin: I\'m hiding')
            }
          })
        }
      })
    },
    popComment(item) {
      this.isPop = true
      this.bookid=item.book_id
    },
    goDetail(id) {
      window.location.href = `./books_detail.html?id=${id}`
    },
    load() {
      this.demo4Value.pullupStatus = 'default'
      this.$nextTick(() => {
        this.$refs.scroller.reset()
      })
    },
    load4() {

      this.demo4Value.pullupStatus = 'up'
      this.$emit('lazyload')
      // setTimeout(() => {

      //   // this.lists.push({
      //   //   title: '婴儿画报2017年第三季度合订本',
      //   //   img: '/static/book.jpg',
      //   //   author: '作者金波',
      //   //   status: '已领取',
      //   // })
      //   setTimeout(() => {
      //     this.demo4Value.pullupStatus = 'default'
      //     this.$nextTick(() => {
      //       this.$refs.scroller.reset()
      //     })
      //   }, 10)
      // }, 2000)
    },
    show(index) {
      if (this.listIndex > index) {
        this.transitionName = 'slide-right'
      } else {
        this.transitionName = 'slide-left'
      }
      this.listIndex = index
    },
    deleteUncollect(id) {
      //取消收藏
      let _this = this;
      fetch('delete', `${url.deleteUncollectBook}/${id}/uncollect?token=${this.token}`).then(res => {
        if (res.status >= 200 && res.status <= 300) {

          this.$vux.toast.show({
            text: '成功取消',
            onShow() {
              //console.log('Plugin: I\'m showing')
            },
            onHide() {
              window.location.href = window.location.href
              //console.log('Plugin: I\'m hiding')
            }
          })
          //window.location.href = window.location.href
          // this.lists.forEach(function(item,index){
          //     if(item.id==id){

          //       window.location.href=window.location.href
          //     }
          //})
          // this.$vux.toast.show({
          //   text: '收藏成功',
          //   type: 'success',
          //   onShow() {
          //     //console.log('Plugin: I\'m showing')
          //   },
          //   onHide() {
          //     window.location.href='./member.html'
          //     //console.log('Plugin: I\'m hiding')
          //   }
          // })
        } else {

          // this.$vux.toast.show({
          //   text: res.data.message,
          //   type: 'warn',
          //   onShow() {
          //     //console.log('Plugin: I\'m showing')
          //   },
          //   onHide() {
          //     //console.log('Plugin: I\'m hiding')
          //   }
          // })
        }
      })
    },
    collect: debounce(function (e, id) {
      //alert(this.token)

      
      
      //收藏
        
      fetch('post', `${url.postCollectBook}/${id}/collect`, {}, { 'headers': this.token }).then(res => {
        if (res.status >= 200 && res.status <= 300) {
          this.$vux.toast.show({
            text: '收藏成功',
            onShow() {
              //console.log('Plugin: I\'m showing')
            },
            onHide() {
              window.location.href = window.location.href
              //console.log('Plugin: I\'m hiding')
            }
          })

        } else {
          this.$vux.toast.show({
            text: res.data.message,
            type: 'warn',
            onShow() {
              //console.log('Plugin: I\'m showing')
            },
            onHide() {
              //console.log('Plugin: I\'m hiding')
            }
          })
        }
      })
    }, 500, {}),
    addCart(item) {

        
      
      let myList=JSON.parse(window.localStorage.getItem('carList'));

      if(myList==null){
        myList=[]
        myList.push(item)
      }else{
        myList.push(item)
      }
    var hash = {};
    myList = myList.reduce(function(item, next) {
        hash[next.id] ? '' : hash[next.id] = true && item.push(next);
        return item
    }, [])
    // console.log(myList);



      // if (myList == null) {
      //   myList.push(item)
      //   carList.push(item)
      // } else {
      //   let flag=false
      //  // carList = JSON.parse(window.localStorage.getItem('carList'))
      //  myList.forEach((item1, index) => {
         
          
          
      //     if (item.id == item1.id) {
      //       flag=true
      //       return
      //     }else{
      //       flag=false  
      //     }
    
      //   })

      //   if(flag==true){
           
      //   }else{
      //     myList.push(item)
      //   }
      // }







      window.localStorage.setItem('carList', JSON.stringify(myList))

      console.log(JSON.parse(window.localStorage.getItem('carList')))

      //console.log(catList)
      //window.localStorage.setItem('carList',catList)

      //console.log(JSON.parse(window.localStorage.getItem('carList')))
      //console.log(JSON.parse(window.localStorage.getItem('carList')))

    }
  },
  directives: {
    TransferDom
  },
  components: {
    Spinner,
    Badge,
    Group,
    Cell,
    Panel,
    XButton,
    Scroller,
    Flexbox,
    FlexboxItem,
    Popup,
    XInput,
    XTextarea
  }
}


